package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.web.app.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.management.monitor.StringMonitor;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private Client client;

    @Override
    public void sendCode(String phone) throws Exception {
        //1.发送之间先检查,redis中是否存在对应的验证码的key [需要导入redis的配置参数]
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        Boolean is = redisTemplate.hasKey(key);
        //1.1 没有 -> 可以继续执行
        //1.2 有 -> 不可以发送,抛出异常
        if (is){
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //2. 发送验证码
        //2.1 准备一个6位的验证码数字
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        //2.2 使用aliyun client发送验证码(1.测试签名 2.测试模板 3.发送的手机号,必须要测试绑定)
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone); //手机号必须绑定测试了
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + sb.toString() + "\"}\n");
        client.sendSms(smsRequest);

        //3. 将手机号key 验证码作为值存储redis中
        redisTemplate.opsForValue().set(key,sb.toString(),RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);
    }
}
